<template>
  <div>
    <!-- 头部面包屑 -->
    <el-breadcrumb>
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 底部卡片 -->
    <el-card>
      <el-button type="primary" @click="shouDialog = true">添加角色</el-button>
      <el-table :data="roleList" border stripe height="525">
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template v-slot="scope">
            <el-row
              :class="['bdbottom', i1 == 0 ? 'bdtop' : '', 'vcenter']"
              v-for="(item1, i1) in scope.row.children"
              :key="item1.id"
            >
              <!-- 渲染一级名称 -->
              <el-col :span="5">
                <el-tag closable @close="removeRightByID(item1.id)"
                  >{{ item1.authName }} </el-tag
                ><i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二级三级名称 -->
              <el-col :span="19">
                <el-row
                  :class="[i2 == 0 ? '' : 'bdtop', 'vcenter']"
                  v-for="(item2, i2) in item1.children"
                  :key="item2.id"
                >
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="removeRightByID(item1.id, item2.id)"
                    >
                      {{ item2.authName }}
                    </el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag
                      type="warning"
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      closable
                      @close="removeRightByID(item1.id, item2.id, item3.id)"
                    >
                      {{ item3.authName }}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="roleName" label="角色名称"> </el-table-column>
        <el-table-column prop="roleDesc" label="角色描述" width="180">
        </el-table-column>
        <el-table-column label="操作">
          <template v-slot="scoped">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="changeEdit(scoped.row)"
              >编辑</el-button
            >
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="delItem(scoped.row.id)"
              >删除</el-button
            >
            <el-button
              type="warning"
              icon="el-icon-setting"
              size="mini"
              @click="showSetRightDialogVisible(scoped.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 弹出添加层 -->
    <el-dialog
      title="添加角色"
      :visible.sync="shouDialog"
      width="50%"
      @close="dialogClosed"
    >
      <el-form
        :model="dialogForm"
        :rules="rules"
        ref="addFormRef"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="dialogForm.name"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input v-model="dialogForm.description"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="shouDialog = false">取 消</el-button>
        <el-button type="primary" @click="addForm">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 改变数据 -->
    <el-dialog title="修改角色" :visible.sync="editDialog">
      <el-form
        :model="editForm"
        :rules="rules"
        ref="changeFormRef"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="editForm.name"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input v-model="editForm.description"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialog = false">取 消</el-button>
        <el-button type="primary" @click="editChange">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配权限对话框 -->
    <el-dialog title="提示" :visible.sync="setRightDialogVisible" width="50%">
      <el-tree
        :data="treeData"
        :props="treeProps"
        show-checkbox
        node-key="id"
        :default-expand-all="true"
        :default-checked-keys="defaultKeys"
        @close="treeClose"
        ref="treeRef"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="alotRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  export default {
    data() {
      return {
        tmpID: '',
        // 分配权限对话框展示与否
        setRightDialogVisible: false,
        // 树形控件展示的数据
        treeData: [],
        // 树形控件展示
        treeProps: {
          label: 'authName',
          children: 'children',
        },
        roleList: [],
        shouDialog: false,
        editDialog: false,
        dialogForm: {
          name: '',
          description: '',
        },
        editForm: {
          name: '',
          description: '',
          id: '',
        },
        rules: {
          name: [{ required: true, message: '角色名称必填', trigger: 'blur' }],
          description: [
            { required: true, message: '角色描述必填', trigger: 'blur' },
          ],
        },
        defaultKeys: [],
      }
    },
    methods: {
      alotRights() {
        let that = this
        const ids = [
          ...that.$refs.treeRef.getCheckedKeys(),
          ...that.$refs.treeRef.getHalfCheckedKeys(),
        ]
        this.setRightDialogVisible = false
        console.log(ids)
      },
      // 权限分配对话框关闭执行的函数
      treeClose() {
        this.defaultKeys = []
      },
      // 分配权限对话框展示函数
      showSetRightDialogVisible(arr) {
        this.treeData = arr.children
        this.getLeafKeys(arr, this.defaultKeys)
        this.setRightDialogVisible = true
      },
      // 递归的函数，获取角色三级权限的id并保存在defaultKeys中
      getLeafKeys(node, arr) {
        // 当节点中没有吃豆人时，就是最后一级
        if (!node.children) {
          console.log('ok')
          return arr.push(node.id)
        }
        node.children.forEach((item) => {
          return this.getLeafKeys(item, arr)
        })
      },
      changeEdit(arr) {
        this.editDialog = true
        this.tmpID = arr.id
        this.editForm.name = arr.roleName
        this.editForm.description = arr.roleDesc
        this.editForm.id = arr.id
      },
      editChange() {
        console.log(this.editForm)
        this.editDialog = false
      },
      // 删除功能
      delItem(id) {
        this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
          .then(async () => {
            const { data: res } = await this.$http.get('roles.php', {
              params: { id },
            })
            if (res) {
              this.roleList.some((item, i) => {
                if (item.id == id) {
                  this.roleList.splice(i, 1)
                  return true
                }
              })
              this.$message({
                type: 'success',
                message: '删除成功!',
              })
            }
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: '已取消删除',
            })
          })
      },
      async getRoleList() {
        const { data: res } = await this.$http.get('roles.php')
        console.log(JSON.parse(res))
        this.roleList = JSON.parse(res)
      },
      dialogClosed() {
        // 重置表单、移除检验
        this.$refs.addFormRef.resetFields()
      },
      // 增加角色
      addForm() {
        // 提交前对表单进行验证
        this.$refs.addFormRef.validate((res) => {
          if (!res) {
            return this.$message.error('数据填写不完整')
          } else {
            let that = this
            let id = parseInt(Math.random() * 999)
            // 生成一个不重复的三位数id
            let t = true
            while (t) {
              if (that.roleList.every((item) => item != id)) {
                t = false
              } else {
                id = parseInt(Math.random() * 999)
              }
            }
            let obj = {
              roleDesc: that.dialogForm.description,
              roleName: that.dialogForm.name,
              id,
            }
            this.roleList.push(obj)
            this.$http
              .get('roles.php', {
                params: {
                  data: obj,
                },
              })
              .then((res) => {
                if (res.data == 'ok') {
                  this.$message.success('数据添加成功')
                }
              })
              .catch((err) => {
                if (err) {
                  this.$message.error('数据添加失败')
                }
              })
            that.shouDialog = false
          }
        })
      },
      removeRightByID(id1, id2 = false, id3 = false) {
        let that = this
        this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
          .then(() => {
            if (id3 === false) {
              if (id2 == false) {
                console.log(id1)
                that.roleList.map((item, i) => {
                  if (item.id == id1) {
                    that.roleList.splice(i, 1)
                    return true
                  }
                })
              } else {
                that.roleList.map((item) => {
                  if (item.id == id1) {
                    return item.children.map((item1, i) => {
                      if (item1.id == id2) {
                        item.children.splice(i, 1)
                        return true
                      }
                    })
                  }
                })
              }
            } else {
              that.roleList.map((item) => {
                if (item.id == id1) {
                  return item.children.map((item1) => {
                    if (item1.id == id2) {
                      return item1.children.map((item2, i) => {
                        if (item2.id == id3) {
                          item2.children.splice(i, 1)
                          console.log(id3)
                          return true
                        }
                      })
                    }
                  })
                  // return item.children.map(item1 => {
                  //   if (item1.id == id2) {

                  //     return item1.children.map((item2,i)=>{
                  //       if(item2.id==id3){
                  //         item1.children.splice(i,1)
                  //         return true
                  //       }
                  //     }

                  //   }
                  // })
                }
              })
            }
            // this.roleList.forEach((item) => {
            //   if (item.id == nId) {
            //     console.log(nId + '内')
            //   }
            // })
          })
          .catch(() => {
            this.$message.info('取消了删除')
          })
      },
    },
    created() {
      this.getRoleList()
    },
  }
</script>

<style>
  .el-tag {
    margin: 7px;
  }
  .bdtop {
    border-top: 1px solid #eee;
  }
  .bdbottom {
    border-bottom: 1px solid #eee;
  }
  .vcenter {
    display: flex;
    align-items: center;
  }
</style>